package org.ofbiz.wvtools.word;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.ofbiz.base.util.FileUtil;


public class WordFreemakerUtils {
 /**
  * https://blog.csdn.net/ai_0922/article/details/82773466
  * office word 2007  测试通过
  * 
  */
	public static void main(String args[]) throws IOException {

    generateWord();

		String wordTemplatePath = "D:/workspace/frame_sever/applications/wvtools/config/word-template/";

		String oldFileName = "demotemplate5.xml";
		String newFileName = "demotemplate52.xml";

//		boolean wordStatus = checkWordTemplate(wordTemplatePath + oldFileName);
//		System.out.println("wordStatus = " + wordStatus);

	 // repairWordTemplate(wordTemplatePath+oldFileName, wordTemplatePath+newFileName);

	}    
	
	

	/**
	 * 
	 * 1, 新建一个word文档模板, 输入内容。
	 * 2, 将该word文件另存为xml格式(注意是另存为,不是直接改扩展名) 
	 * 3, 将xml文件上传服务器 
	 * 4, 用执行服务导出生成的word
	 * 
	 */
	private static void generateWord() throws IOException {
		FreemarkerWordTemplateUtils f = new FreemarkerWordTemplateUtils();
		f.init();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("参数1", "中文参数1");
		map.put("参数2", "中文参数2");
		map.put("参数3", "中文参数3");

		// f.processWordTemplate("d://dd.doc", "fffddd.ftl", map);
		f.processWordTemplate("d://dd5.doc", "demotemplate52.xml", map);

	}

	/**
	 * 修复word中参数被换行的情况
	 * 
	 * @param oldFilePath
	 * @param newFilePath
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static boolean checkWordTemplate(String oldFilePath) throws FileNotFoundException, IOException {
		boolean result = true;
		StringBuffer oldContent = FileUtil.readTextFile(oldFilePath, true);
		String regEx = "\\{.+?\\}";
		Pattern pattern = Pattern.compile(regEx);
		Matcher matcher = pattern.matcher(oldContent);// 正则匹配字符串{****}
		int count = 0;
		while (matcher.find()) {
			count++;
			System.out.println("found: " + count + " : " + matcher.start() + " - " + matcher.end());
			String oldSubString = oldContent.substring(matcher.start() - 1, matcher.end());

			System.out.println("oldSubString = " + oldSubString);

			String key_regex = "\\<.*?>";

			String newParamKey = oldSubString.replaceAll(key_regex, "");
			System.out.println("newParamKey = " + newParamKey);
			String oldParamKey = newParamKey.substring(2, newParamKey.length() - 1);
			System.out.println("oldParamKey = " + oldParamKey);

			if (!oldSubString.equals(newParamKey)) {
				System.out.println("this word template need repair!");
				result = false;
			}
			if (!newParamKey.contains("${")) {
				System.out.println("this word template need repair! " + newParamKey);
				result = false;
			}
			if (!newParamKey.contains("}")) {
				System.out.println("this word template need repair! " + newParamKey);
				result = false;
			}
		}

		return result;

	}

	/**
	 * 修复word中参数被换行的情况
	 * 1 处理$和{分离
	 * 2 过滤出来 ${ 和 }中间的内容    子字符串
	 * 3 把${xxxxx关键字xxxxx} 替换为xxxxx${关键字}xxxxx
	 * 4 输出
	 */
	public static void repairWordTemplate(String oldFilePath, String newFilePath)throws FileNotFoundException, IOException {
		StringBuffer oldContentStringBuffer = FileUtil.readTextFile(oldFilePath, true);
		String oldContent = new String(oldContentStringBuffer);
		oldContent = replaceXWPFRun(oldContent);

		String regEx = "\\{.+?\\}";
		Pattern pattern = Pattern.compile(regEx);
		Matcher matcher = pattern.matcher(oldContent);// 正则匹配字符串{****}
		int count = 0;
		List<Map> list = new ArrayList();
		while (matcher.find()) {
			Map m = new HashMap();
			count++;
			System.out.println("found: " + count + " : " + matcher.start() + " - " + matcher.end());
			String oldSubString = oldContent.substring(matcher.start() - 1, matcher.end());
			System.out.println("oldSubString = " + oldSubString);

			String key_regex = "\\<.*?>";

			String newParamKey = oldSubString.replaceAll(key_regex, "");
			System.out.println("newParamKey = " + newParamKey);
			String oldParamKey = newParamKey.substring(2, newParamKey.length() - 1);
			System.out.println("oldParamKey = " + oldParamKey);
			
			
			String newSubString = oldSubString.replace("${", "");
			newSubString = newSubString.replace("}", "");
			newSubString = newSubString.replace(oldParamKey, newParamKey);
			System.out.println("newSubString = " + newSubString);
			
			
			m.put("oldSubString", oldSubString);
			m.put("newSubString", newSubString);
			
			if(oldSubString.length()!=newSubString.length()) {
				System.out.println("oldSubString.length = " + oldSubString.length());
				System.out.println("newSubString.length = " + newSubString.length());
				
				String newParamKey2 =getOtherText(key_regex,oldSubString);
				System.out.println("newParamKey2 = " + newParamKey2);
				System.out.println("newParamKey2.length = " + newParamKey2.length());
				newSubString =newParamKey+newParamKey2;
				m.put("newSubString", newSubString);
				System.out.println("newSubString = " + newSubString);
				
			}
			
			
			list.add(m);
		}
		String newContent = new String(oldContent);
		for (Map map : list) {
			String oldSubString = (String) map.get("oldSubString");
			String newSubString = (String) map.get("newSubString");
			newContent = newContent.replace(oldSubString, newSubString);
		}
		FileUtil.writeString(newFilePath, newContent);

	}

	/**
	 * 合并被分开的$和{ 为 ${
	 * 
	 * @param oldContent
	 * @return
	 */
	private static String replaceXWPFRun(String oldContent) {
		String newContent = oldContent;
		int repair1 = oldContent.indexOf("<w:t>$</w:t>");
		int repair2 = oldContent.indexOf("<w:t>{");

		System.out.println("repair1 = " + repair1);
		System.out.println("repair2 = " + repair2);
		if ((repair1 > 0) && (repair2 > 0)) {
			oldContent = oldContent.replace("<w:t>$</w:t>", "<w:t></w:t>");
			oldContent = oldContent.replace("<w:t>{", "<w:t>${");

			newContent = replaceXWPFRun(oldContent);
		}

		return newContent;
	}
	
	private static String getOtherText(String key_regex,String inputStr) {
		
		String result = "";
		
		   Pattern p = Pattern.compile(key_regex);
		   Matcher m = p.matcher(inputStr);
		   while (m.find()) {
		    result=result+m.group(0).substring(0, m.group().length());
		   }
		   return result;
		  }
		 
		

}
